Skip to content

fix(chat): thread UI-selected model into the chat workflow#638

Closed
arpitgupta1214 wants to merge 3 commits into
testfrom
fix/workflow-model-selection
Closed

fix(chat): thread UI-selected model into the chat workflow#638
arpitgupta1214 wants to merge 3 commits into
testfrom
fix/workflow-model-selection

Conversation

@arpitgupta1214

@arpitgupta1214 arpitgupta1214 commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator

Model selection from the chat UI was ignored by the workflow path — every request billed the default model.

The UI already sends the selected model in the POST /api/chat/workflow body, but chatWorkflowBodySchema had no model field (Zod stripped it) and the handler only read the chat's persisted model_id (null until a chat is PATCHed). Now the schema accepts model and the handler uses validated.model ?? chat.model_id ?? DEFAULT_MODEL_ID.

Test plan

  • pnpm test lib/chat/__tests__/validateChatWorkflow.test.ts lib/chat/__tests__/handleChatWorkflowStream.test.ts — added cases for accepting model, omitting it, and preferring it over a persisted model_id.

🤖 Generated with Claude Code


Summary by cubic

Honor the UI-selected model in the chat workflow so requests use the chosen model instead of the default. The request schema now accepts model, and the handler prefers it over chat.model_id and the default.

  • Bug Fixes

    • Added optional model to chatWorkflowBodySchema.
    • In handleChatWorkflowStream, use validated.model ?? chat.model_id ?? DEFAULT_MODEL_ID.
    • Tests: single cases verify UI model pass-through and precedence over a persisted model_id.
  • Refactors

    • Trimmed model-selection comments to one-liners for clarity.

Written for commit d5e63a0. Summary will update on new commits.

Review in cubic

The chat UI sends the selected model in the POST /api/chat/workflow
body, but the schema stripped it and the handler only read the chat's
persisted model_id (null for new chats) — so every request billed the
default model. Accept `model` in the schema and prefer
validated.model ?? chat.model_id ?? DEFAULT_MODEL_ID.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@vercel

vercel Bot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
api Ready Ready Preview Jun 3, 2026 11:44pm

Request Review

@coderabbitai

coderabbitai Bot commented Jun 3, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@arpitgupta1214, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 3 minutes and 22 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: df851da6-73a8-49a7-beba-0bec471fcff2

📥 Commits

Reviewing files that changed from the base of the PR and between 11ca945 and d5e63a0.

⛔ Files ignored due to path filters (2)
  • lib/chat/__tests__/handleChatWorkflowStream.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/chat/__tests__/validateChatWorkflow.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
📒 Files selected for processing (2)
  • lib/chat/handleChatWorkflowStream.ts
  • lib/chat/validateChatWorkflow.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/workflow-model-selection

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 4 files

Confidence score: 4/5

  • This PR is likely safe to merge with minimal risk because the reported issue is moderate severity (5/10) and scoped to model-selection fallback behavior rather than a broad workflow break.
  • In lib/chat/handleChatWorkflowStream.ts, whitespace-only model overrides are currently treated as valid, which can skip persisted/default fallback and lead to unexpected model choice for affected requests.
  • The issue appears concrete (confidence 8/10) but localized, so impact should be limited to inputs where model is blank/whitespace rather than all chat flows.
  • Pay close attention to lib/chat/handleChatWorkflowStream.ts - ensure model values are trimmed/validated so fallback logic still applies for empty overrides.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="lib/chat/handleChatWorkflowStream.ts">

<violation number="1" location="lib/chat/handleChatWorkflowStream.ts:97">
P2: Whitespace-only `model` values are treated as valid overrides, bypassing fallback to persisted/default model.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant UI as Chat UI
    participant API as API Route (POST /api/chat/workflow)
    participant Val as validateChatWorkflow
    participant Handler as handleChatWorkflowStream
    participant DB as Database
    participant Workflow as Chat Workflow

    Note over UI,Workflow: Chat Model Selection Flow

    UI->>API: POST with body { messages, model: "openai/gpt-5.4-mini" }
    API->>Val: validateChatWorkflow(request)
    Val->>Val: Parse body with chatWorkflowBodySchema
    Note over Val: Zod schema now accepts optional model field
    alt Valid body with model
        Val-->>API: { model: "openai/gpt-5.4-mini", ... }
    else Valid body without model
        Val-->>API: { model: undefined, ... }
    end

    API->>Handler: handleChatWorkflowStream(request)
    Handler->>DB: selectChats(chatId)
    DB-->>Handler: { model_id: "anthropic/claude-opus-4.6" } (or null)

    alt validated.model is provided
        Note over Handler: Use UI-selected model
        Handler->>Handler: modelId = "openai/gpt-5.4-mini"
    else validated.model is undefined AND chat.model_id exists
        Note over Handler: Use persisted chat model
        Handler->>Handler: modelId = "anthropic/claude-opus-4.6"
    else neither model source is available
        Note over Handler: Fall back to default
        Handler->>Handler: modelId = DEFAULT_MODEL_ID
    end

    Handler->>Workflow: start workflow with { modelId }
    Workflow-->>Handler: Stream response
    Handler-->>UI: Streaming response with correct model billing
Loading

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

// persisted model_id, then the default. Without this the workflow
// always billed DEFAULT_MODEL_ID since model_id is null until a
// chat is explicitly PATCHed.
const modelId = validated.model ?? chat.model_id ?? DEFAULT_MODEL_ID;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Whitespace-only model values are treated as valid overrides, bypassing fallback to persisted/default model.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/chat/handleChatWorkflowStream.ts, line 97:

<comment>Whitespace-only `model` values are treated as valid overrides, bypassing fallback to persisted/default model.</comment>

<file context>
@@ -90,7 +90,11 @@ export async function handleChatWorkflowStream(request: NextRequest): Promise<Re
+  // persisted model_id, then the default. Without this the workflow
+  // always billed DEFAULT_MODEL_ID since model_id is null until a
+  // chat is explicitly PATCHed.
+  const modelId = validated.model ?? chat.model_id ?? DEFAULT_MODEL_ID;
   const recoupOrgId = session.clone_url
     ? (extractOrgId(session.clone_url) ?? undefined)
</file context>
Suggested change
const modelId = validated.model ?? chat.model_id ?? DEFAULT_MODEL_ID;
const requestedModelId = validated.model?.trim();
const modelId = requestedModelId ? requestedModelId : chat.model_id ?? DEFAULT_MODEL_ID;

arpitgupta1214 and others added 2 commits June 4, 2026 05:12
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@arpitgupta1214

Copy link
Copy Markdown
Collaborator Author

E2E verification (live, against this PR's preview)

Drove the test chat UI (chat-git-test-recoup.vercel.app) pointed at this PR's preview API via ?api=, selected Gemini 2.5 Flash (google/gemini-2.5-flash-lite), and sent a message. A controlled before/after fell out naturally because two turns in the same chat (same UI selection, same chat with DB model_id = null) were served by different backends:

Turn Backend metadata.modelId (billed) Result
1 test-recoup-api (without this fix) anthropic/claude-haiku-4.5 ← default 🐛 selection ignored
2 this PR's preview (with fix) google/gemini-2.5-flash-lite ← selected ✅ selection honored

The only variable is the backend: unfixed → billed the hardcoded default; fixed → billed the user's choice.

Confirmed two independent ways for turn 2:

  • Live workflow response stream emitted modelId: "google/gemini-2.5-flash-lite" from POST {preview}/api/chat/workflow.
  • Persisted chat_messages metadata (read back via GET /api/sessions/{sessionId}/chats/{chatId}) shows the same.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 4 files (changes from recent commits).

Requires human review: Auto-approval blocked by 1 unresolved issue from previous reviews.

Re-trigger cubic

@sweetmantech

Copy link
Copy Markdown
Contributor

Closing — after checking the open-agents reference, threading model through the workflow request body isn't their pattern, and we're deliberately building on their mental models.

How open-agents resolves the model: server-side, from the persisted chat.modelId — not the request body.

  • apps/web/app/api/chat/route.ts:182-190selectedModelId = sanitize(chat.modelId) ?? chat.modelId ?? null, threaded into start(runAgentWorkflow, [{ selectedModelId, modelId }]) at :231-232. (The body.model reference at workflows/chat.ts:213 is only a summarizeRequestBody telemetry helper, not the resolution path.)

Our handler already matches this: lib/chat/handleChatWorkflowStream.ts:93 reads chat.model_id ?? DEFAULT_MODEL_ID. So no api change is needed to honor the selected model — the model just has to be in chats.model_id before the send.

The actual fix (open-agents-faithful), no request-body change:

  1. Persist the picker selection to chats.model_id on change (PATCH) + hydrate existing chats — chat#1779.
  2. Set chats.model_id at chat creation to the user's selected/default model, mirroring open-agents apps/web/app/api/sessions/route.ts:266 (modelId: preferences.defaultModelId). Today lib/sessions/createSessionHandler.ts:69-73 inserts the initial chat with no model_id, so it falls to the column default ('anthropic/claude-haiku-4.5') — that's the root of "every new chat bills haiku". This is the piece chat#1779 still needs.

Tracked on recoupable/chat#1767. Thanks @arpitgupta1214 — good prompt to go verify against the reference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants